package com.app.conf;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.app.mapper.CustomerMapper;
import com.app.mapper.MatchingSuccessfulMapper;
import com.app.model.*;
import com.app.server.WebSocketSever;
import com.app.service.*;
import com.app.util.*;
import com.app.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 定时任务配置
 *
 * @author Pactera
 */
@Slf4j
@Configuration
@EnableScheduling
public class SchedulingConfig {

    @Resource
    private RedisService redisService = SpringUtils.getBean(RedisService.class);
    @Resource
    EnterpriseService enterpriseService;

    @Resource
    JobPublishService jobPublishService;

    @Resource
    WorkApplyService workApplyService;
    @Resource
    JobIntentionService jobIntentionService;

    @Resource
    BrowseNumberService browseNumberService;

    @Resource
    JobFairCompanyService jobFairCompanyService;

    @Resource
    CustomerService customerService;
    @Resource
    ComRecruitersService comRecruitersService;

    @Resource
    NewsService newsService;

    @Resource
    ComResumeNumberService comResumeNumberService;
    @Resource
    QuestionnaireInvestigationService questionnaireInvestigationService;
    @Resource
    SkillTrainingService skillTrainingService;
    @Resource
    VideoTrainService videoTrainService;
    @Resource
    TrainEnrollService trainEnrollService;
    @Resource
    CusWorkExperienceService cusWorkExperienceService;
    @Resource
    CusEducationService cusEducationService;
    @Resource
    PositionService positionService;
    @Resource
    CustomerMapper customerMapper;
    @Resource
    HelpRecordService helpRecordService;
    @Resource
    MatchingSuccessfulMapper matchingSuccessfulMapper;
    @Resource
    private LiveService liveService = SpringUtils.getBean(LiveService.class);

    private LivePortendService livePortendService = SpringUtils.getBean(LivePortendService.class);

    private UserService userService = SpringUtils.getBean(UserService.class);

    //@Scheduled(cron = "0 0 0 * * *") // 每天凌晨执行一次(0:0:0)
    //@Scheduled(cron = "0 */10 * * * ?") // 每10分钟执行一次
    @Scheduled(cron = "*/10 * * * * ?") // 每10秒执行一次
    public void liveHeartbeat() {
        try {
            List<String> keys = new ArrayList<String>(redisService.keys("akesaiRoom"));

            for (int i = 0; i < keys.size(); i++) {

                int isClose = 0;
                List<WebSocketVO> webSocketVOList = (List<WebSocketVO>) redisService.getStringKey(keys.get(i));
                for (int j = 0; j < webSocketVOList.size(); j++) {
                    //查询35秒未心跳用户，删除
                    int difference = DateUtil.calLastedTime(webSocketVOList.get(j).getHeartbeatTime());
                    if (difference >= 35) {
                        //如果是主播删除整个房间
                        if (webSocketVOList.get(j).getAction() == 1) {
                            isClose = 1;

                        } else {//如果是观众，删除在线观众
                            WebSocketVO vo = webSocketVOList.get(j);
                            webSocketVOList.remove(j);
                            redisService.deleteKey(vo.getRoomId());
                            redisService.setStringKey(vo.getRoomId(), webSocketVOList);
                        }
                    }
                }
                // 确认主播掉线，删除直播间
                if (isClose == 1) {
                    for (int j = 0; j < webSocketVOList.size(); j++) {
                        JSONObject json = new JSONObject();
                        json.put("number", 0);
                        //直播redis数据长度0时为直播关闭
                        json.put("state", 0);
                        WebSocketSever.sendMessageByUser(webSocketVOList.get(j).getUserId(), json.toString());
                    }
                    redisService.deleteKey(keys.get(i));
                    liveService.liveEnd(keys.get(i));
                }
            }

        } catch (Exception e) {
            log.error("定时任务出错", e);
        }
    }

    @Scheduled(cron = "0 */1 * * * ?") // 每10分钟执行一次
    public void advertisementHeartbeat() {
        //查询可开启直播权限
        List<LivePortendModel> openList = livePortendService.getModelListByOnOpen();
        for (int i = 0; i < openList.size(); i++) {
            openList.get(i).setStatus(1);
            livePortendService.update(openList.get(i));
            UserModel user = userService.getUserById(openList.get(i).getUserId());
            user.setLivePower(1);
            userService.update(user);
        }
        //查询可关闭直播权限
        List<LivePortendModel> closeList = livePortendService.getModelListByOnClose();
        for (int i = 0; i < closeList.size(); i++) {
            closeList.get(i).setStatus(3);
            livePortendService.update(closeList.get(i));
            UserModel user = userService.getUserById(closeList.get(i).getUserId());
            user.setLivePower(0);
            userService.update(user);
        }
    }



    @Scheduled(cron = "*/10 * * * * ?") // 每10秒执行一次
    public void getCusPlaceList() {
        try {
            int enterpriseCount = comRecruitersService.getCountByGroup(null,null,2);//企业数
            int jobCount = jobPublishService.countAll();//岗位数
            int jobPassCount = jobPublishService.passCount();//在招岗位
            int browseCount = browseNumberService.getModelCountByTime("2023-07-14 00:00:00");//浏览数
            int recruitCount = browseNumberService.getCount(1);
            int oddJobCount = browseNumberService.getCount(2);
            int customerCount = customerService.getModelCountByTime("2023-07-14 00:00:00",null,null,2);//人数
            int delivererCount = workApplyService.countGroup();//简历投递人
            int mateCount = matchingSuccessfulMapper.selectCount();//匹配成功
            int deliveryCount = workApplyService.countAll(null,null,2);//简历投递量
            int intentionCount = jobIntentionService.getCountByGroup();
            //int male = questionnaireInvestigationService.selectMale();//未就业男
//            int female = questionnaireInvestigationService.selectFemale();//未就业女
//            int[] agePercent = questionnaireInvestigationService.selectAgePercent();
//            List<QuestionnaireInvestigationModel> wishWork = questionnaireInvestigationService.selectWishWorkCount();
//            List<QuestionnaireInvestigationModel> trainWork = questionnaireInvestigationService.selectTrainWork();
            ValueAndNameVo education = cusEducationService.education();
            List<CusWorkExperienceModel> cusWorkExperienceModels = cusWorkExperienceService.selectExp();
            Integer train = trainEnrollService.selectCount();//报名
            Integer skill = skillTrainingService.selectCount();//培训机构
            Integer video = videoTrainService.selectCount();//培训视频
            int[] customerModels = customerService.agePie();
            List<WorkApplyModel> employers = workApplyService.employers();
            List<WorkApplyModel> post = workApplyService.post();//用人岗位
            int[] sexCount = customerService.selectSexCount();
            //帮扶三次未就业
            Integer helpThree = questionnaireInvestigationService.getHelpThreeCount();
            //帮扶情况
            HelpCountVo helpCountVo = questionnaireInvestigationService.getHelpCount();

            //在家务农
            Integer agriculture = questionnaireInvestigationService.agriculture();
            //外出务工
            Integer industry = questionnaireInvestigationService.industrial();
            //全市农村劳动力
            Integer ruralLaborersCount = questionnaireInvestigationService.ruralLaborersCount();
//            //城镇有就业意愿人数
            Integer workWillingCount = questionnaireInvestigationService.workWillingCount();
//            //全市城镇未就业人数
            Integer cityNoWorkCount = questionnaireInvestigationService.cityNoWorkCount();
            //城镇就业率
            Integer cityCount = questionnaireInvestigationService.cityCount();
//            //农村劳动力意向就业岗位：男、女（柱状图）
            Integer[] unemployed = questionnaireInvestigationService.Unemployed();
            //微信/短信/平台
            Integer[] WxCount = helpRecordService.getCount();
            //1、供求行业分组：行业供给数、行业需求数（柱状图）
            //帮扶情况
            UnemploymentSituationVo unemploymentSituationVo = questionnaireInvestigationService.getWorkSituation();
            //督办情况
            UnemploymentSituationVo handleVo = questionnaireInvestigationService.getHandleSituation();
            //行业需求数
            List<JobPublishModel> industryDemand = jobPublishService.supplyAndDemandIndustries();
            //行业供给数
            List<JobIntentionModel> industrySupply = jobIntentionService.supplyAndDemandIndustries();
            //2、需求前10职业排行：（柱状图）
            List<JobPublishModel> jobPublishModels = jobPublishService.selectPost();
            //3、供给前10职业排行：（柱状图）
            List<JobIntentionModel> jobIntentionModels = jobIntentionService.selectPost();
            //4、产业用工情况：服务业、农业、制造业
            //各县市访问量趋势
            List<Integer> trendOfVisits = customerService.selectTrendOfVisits();
            //未就业人员意向就业岗位(TOP20)
            List<QuestionnaireInvestigationModel> unemployedPost = questionnaireInvestigationService.unemployedPost();
            IndexCountVo vo = new IndexCountVo();
            vo.setEnterpriseCount(42+(enterpriseCount)*3);
            vo.setJobCount(128+(jobCount)*3);
            vo.setJobPassCount(128+(jobCount)*3);
            vo.setBrowseCount(5982+(browseCount*3));
            vo.setCustomerCount(1402+(customerCount)*3);
            vo.setDelivererCount(delivererCount*3);
            vo.setDeliveryCount(165+(deliveryCount)*3);
//            vo.setDeliveryCount(deliveryCount);
            vo.setIntentionCount(intentionCount*3);
            vo.setEducationPercent(education);
            vo.setCusWorkExperienceModels(cusWorkExperienceModels);
            vo.setTrain(train);
            vo.setSkill(skill);
            vo.setVideo(video);
            vo.setCustomerModels(customerModels);
            vo.setEmployers(employers);
            vo.setPost(post);
            vo.setAgriculture(agriculture);
            vo.setIndustry(industry);
            vo.setRuralLaborersCount(ruralLaborersCount);
            vo.setWorkWillingCount(workWillingCount);
            vo.setCityNoWorkCount(cityNoWorkCount);
            vo.setCityCount(cityCount);
            vo.setJobPublishModels(jobPublishModels);
            vo.setJobIntentionModels(jobIntentionModels);
            vo.setUnemployed(unemployed);
            vo.setSexCount(sexCount);
            vo.setRecruitCount(recruitCount);
            vo.setOddJobCount(oddJobCount);
            vo.setTrendOfVisits(trendOfVisits);
            vo.setIndustryDemand(industryDemand);
            vo.setIndustrySupply(industrySupply);
            vo.setUnemploymentSituationVo(unemploymentSituationVo);
            vo.setHelpThree(helpThree);
            vo.setHandleVo(handleVo);
            vo.setUnemployedPost(unemployedPost);
            vo.setHelpCountVo(helpCountVo);
            vo.setWxCount(WxCount);
            vo.setMateCount(mateCount);
            redisService.deleteKey("akesaiIndexCount");
            redisService.setStringKey("akesaiIndexCount", vo);
        } catch (Exception e) {
            log.error("定时任务出错", e);
        }
    }
    @Scheduled(cron = "0 0/60 * * * ?") // 每10秒执行一次
    public void getTalentJobIntention() {
        try {
            Map<String, Integer> resultMap = new HashMap<>();
            List<PositionModel> parent = positionService.parent();//查父级
            List<PositionModel> childLevel = positionService.childLevel();//查子级
            List<PositionModel> grandchildLevel = positionService.grandchildLevel();//查孙级
            List<JobIntentionModel> jobIntentionModels = jobIntentionService.selectAll();
            for (int i = 0; i < jobIntentionModels.size(); i++) {
                Integer count = 1;
                for (int i1 = 0; i1 < grandchildLevel.size(); i1++) {
                    if (jobIntentionModels.get(i).getPost() == grandchildLevel.get(i1).getId()) {
                        for (int i2 = 0; i2 < childLevel.size(); i2++) {
                            if (grandchildLevel.get(i1).getFatherCode().equals(childLevel.get(i2).getPostCode())) {
                                for (int i3 = 0; i3 < parent.size(); i3++) {
                                    if (childLevel.get(i2).getFatherCode().equals(parent.get(i3).getPostCode())) {
                                        String key = parent.get(i3).getJobTitle();
                                        if (resultMap.containsKey(key)) {
                                            resultMap.replace(key, resultMap.get(key) + 1);
                                        } else {
                                            resultMap.put(key, count);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            IndexCountVo vo = new IndexCountVo();
            vo.setResultMap(resultMap);
            redisService.deleteKey("akesaiTalentJobIntention");
            redisService.setStringKey("akesaiTalentJobIntention", vo);
        } catch (Exception e) {
            log.error("定时任务出错", e);
        }
    }

    @Scheduled(cron = "0 0/60 * * * ?") // 每10秒执行一次
    public void getTalentList() {
        try {
            IndexCountVo vos = new IndexCountVo();
            List<CustomerModel> customerModels = customerMapper.selectList(null);
            for (int i = 0; i < customerModels.size(); i++) {
                if (customerModels.get(i).getBirthday() != null)//年龄
                {
                    Timestamp time = new Timestamp(new SimpleDateFormat("yyyy-MM-dd").parse(customerModels.get(i).getBirthday() + "-01").getTime());
                    String date = DateUtil.yearCompare(time, CommonHelp.getNowTimestamp());
                    customerModels.get(i).setAge(Integer.valueOf(date));
                } else {
                    customerModels.get(i).setAge(0);
                }
            }
            int[] arr = new int[6];
            //20以下
            List<CustomerModel> collect = customerModels.stream()
                    .filter(CustomerModel -> CustomerModel.getAge() < 20)
                    .collect(Collectors.toList());
            // 20-30
            List<CustomerModel> collect1 = customerModels.stream()
                    .filter(CustomerModel -> CustomerModel.getAge() >= 20 && CustomerModel.getAge() < 30)
                    .collect(Collectors.toList());
            // 30-40
            List<CustomerModel> collect2 = customerModels.stream()
                    .filter(CustomerModel -> CustomerModel.getAge() >= 30 && CustomerModel.getAge() < 40)
                    .collect(Collectors.toList());
            // 40-50
            List<CustomerModel> collect3 = customerModels.stream()
                    .filter(CustomerModel -> CustomerModel.getAge() >= 40 && CustomerModel.getAge() < 50)
                    .collect(Collectors.toList());
            // 50以上
            List<CustomerModel> collect4 = customerModels.stream()
                    .filter(CustomerModel -> CustomerModel.getAge() >= 50)
                    .collect(Collectors.toList());

            QueryWrapper<CustomerModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("sex", 1);
            Integer male = customerMapper.selectCount(queryWrapper);//男数
            QueryWrapper<CustomerModel> queryWrapper1 = new QueryWrapper<>();
            queryWrapper.eq("sex", 1);
            Integer female = customerMapper.selectCount(queryWrapper1);//女数
            arr[0] = collect.size();
            arr[1] = collect1.size();
            arr[2] = collect2.size();
            arr[3] = collect3.size();
            arr[4] = collect4.size();
            arr[5] = customerModels.size();
            vos.setMale(male);
            vos.setFemale(female);
            vos.setAgePercent(arr);
            redisService.deleteKey("akesaiTalent");
            redisService.setStringKey("akesaiTalent", vos);
        } catch (Exception e) {
            log.error("定时任务出错", e);
        }
    }

    /**
     * 使用频率分析
     */
    @Scheduled(cron = "0 */1 * * * ?") // 每10秒执行一次
    public void getCustomerUseCount() {
        List<Integer> frequencyList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = format.format(CommonHelp.getNowTimestamp());
        String today = format.format(CommonHelp.getNowTimestamp());//今天
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.add(Calendar.DAY_OF_MONTH, -3);
        Date beforeMonth = calendar.getTime();
        String three = format.format(beforeMonth);//3天
        Calendar calendar2 = Calendar.getInstance(); //得到日历
        calendar2.add(Calendar.DAY_OF_MONTH, -7);
        Date beforeMonth2 = calendar2.getTime();
        String seven = format.format(beforeMonth2);//7天
        Calendar calendar3 = Calendar.getInstance(); //得到日历
        calendar3.add(Calendar.DAY_OF_MONTH, -15);
        Date beforeMonth3 = calendar3.getTime();
        String fifteen = format.format(beforeMonth3);//15天
        Calendar calendar4 = Calendar.getInstance(); //得到日历
        calendar4.add(Calendar.DAY_OF_MONTH, -30);
        Date beforeMonth4 = calendar4.getTime();
        String month = format.format(beforeMonth4);//30天
        frequencyList.add(customerService.getModelCountByLoginTime(today,endTime));
        frequencyList.add(customerService.getModelCountByLoginTime(three,endTime));
        frequencyList.add(customerService.getModelCountByLoginTime(seven,endTime));
        frequencyList.add(customerService.getModelCountByLoginTime(fifteen,endTime));
        frequencyList.add(customerService.getModelCountByLoginTime(month,endTime));
        redisService.deleteKey("akesaiLoginFrequency");
        redisService.setStringKey("akesaiLoginFrequency", frequencyList);
    }

    /**
     * 个人注册流程质量分析
     */
    @Scheduled(cron = "0 */1 * * * ?") // 每10秒执行一次
    public void getCustomerQualityCount() {
        List<Integer> qualityList = new ArrayList<>();
        int intentionCount = jobIntentionService.getCountByGroup();
        int cusCount = customerService.getModelCountByNull();
        int countAll = customerService.getCountAll();
        qualityList.add(countAll);//完成注册用户数
        qualityList.add(cusCount);//注册个人信息环节留存
        qualityList.add(countAll-intentionCount-cusCount);
        redisService.deleteKey("akesaiQuality");
        redisService.setStringKey("akesaiQuality", qualityList);

    }

    /**
     * 企业注册流程质量分析
     */
    @Scheduled(cron = "0 */1 * * * ?") // 每10秒执行一次
    public void getComQualityCount() {
        List<Integer> qualityList = new ArrayList<>();
        int comCount = userService.getNosRegisterCount();
        int cusCount = customerService.getModelCountByNull();
        int noPublish = comRecruitersService.getNotPublishCount();
        qualityList.add(cusCount);//完成注册企业数
        qualityList.add(comCount);//注册企业信息环节留存
        qualityList.add(noPublish);
        redisService.deleteKey("akesaiComQuality");
        redisService.setStringKey("akesaiComQuality", qualityList);
    }

    /**
     * 获取近15天访问量
     */
//    @Scheduled(cron = "0 0 0 * * *") // 每天凌晨执行一次(0:0:0)
    @Scheduled(cron = "0 */10 * * * ?") // 每10分钟执行一次
//    @Scheduled(cron = "0 */1 * * * ?") // 每10秒执行一次
    public void getTrendOfVisits15Day() {
        List<Integer> valueList = new ArrayList<>();
        List<String> dayList = CommonUtil.getDayList(15);
        for (String date : dayList) {
            String startTime = date + " 00:00:00";
            String endTime = date + " 23:59:59";
            int browseCount = browseNumberService.getBrowseCount(startTime, endTime);
            valueList.add(browseCount);
        }
        redisService.deleteKey("akesai15DayCount");
        redisService.setStringKey("akesai15DayCount", valueList);
    }
    /**
     * 用户使用频率分析
     */
    @Scheduled(cron = "0 */10 * * * ?") // 每10分钟执行一次
//    @Scheduled(cron = "0 */1 * * * ?") // 每10秒执行一次
    public void getUseFrequencyCount() {
        List<Integer> useFrequencyList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String endTime = format.format(CommonHelp.getNowTimestamp());
        String today = format.format(CommonHelp.getNowTimestamp());//今天
        Calendar calendar = Calendar.getInstance(); //得到日历
        calendar.add(Calendar.DAY_OF_MONTH, -3);
        Date beforeMonth = calendar.getTime();
        String three = format.format(beforeMonth);//3天
        Calendar calendar2 = Calendar.getInstance(); //得到日历
        calendar2.add(Calendar.DAY_OF_MONTH, -7);
        Date beforeMonth2 = calendar2.getTime();
        String seven = format.format(beforeMonth2);//7天
        Calendar calendar3 = Calendar.getInstance(); //得到日历
        calendar3.add(Calendar.DAY_OF_MONTH, -15);
        Date beforeMonth3 = calendar3.getTime();
        String fifteen = format.format(beforeMonth3);//15天
        Calendar calendar4 = Calendar.getInstance(); //得到日历
        calendar4.add(Calendar.DAY_OF_MONTH, -30);
        Date beforeMonth4 = calendar4.getTime();
        String month = format.format(beforeMonth4);//30天

        useFrequencyList.add(browseNumberService.getBrowseCount(today,endTime));
        useFrequencyList.add(browseNumberService.getBrowseCount(three,endTime));
        useFrequencyList.add(browseNumberService.getBrowseCount(seven,endTime));
        useFrequencyList.add(browseNumberService.getBrowseCount(fifteen,endTime));
        useFrequencyList.add(browseNumberService.getBrowseCount(month,endTime));
        redisService.deleteKey("akesaiUseFrequency");
        redisService.setStringKey("akesaiUseFrequency", useFrequencyList);
    }
}
